home *** CD-ROM | disk | FTP | other *** search
/ MacTech 1 to 12 / MacTech-vol-1-12.toast / Reference / FAQs on CD / C++ FAQ Lite (6⁄7) < prev    next >
Encoding:
Text File  |  1997-01-17  |  48.3 KB  |  1,036 lines  |  [TEXT/R*ch]

  1. Archive-name: C++-faq/part6
  2. Posting-Frequency: monthly
  3. Last-modified: Jan 1, 1997
  4. URL: http://www.cerfnet.com/~mpcline/c++-faq-lite/
  5.  
  6. AUTHOR: Marshall Cline / cline@parashift.com / Paradigm Shift, Inc. /
  7. One Park St. / Norwood, NY 13668 / 315-353-6100 (voice) / 315-353-6110 (fax)
  8.  
  9. COPYRIGHT: This posting is part of "C++ FAQ Lite."  The entire "C++ FAQ Lite"
  10. document is Copyright(C) 1991-96 Marshall P. Cline, Ph.D., cline@parashift.com.
  11. All rights reserved.  Copying is permitted only under designated situations.
  12. For details, see section [1].
  13.  
  14. NO WARRANTY: THIS WORK IS PROVIDED ON AN "AS IS" BASIS.  THE AUTHOR PROVIDES NO
  15. WARRANTY WHATSOEVER, EITHER EXPRESS OR IMPLIED, REGARDING THE WORK, INCLUDING
  16. WARRANTIES WITH RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
  17. PURPOSE.
  18.  
  19. C++-FAQ-Lite != C++-FAQ-Book: This document, C++ FAQ Lite, is not the same as
  20. the C++ FAQ Book.  The book (C++ FAQs, Cline and Lomow, Addison-Wesley) is 500%
  21. larger than this document, and is available in bookstores.  For details, see
  22. section [3].
  23.  
  24. ==============================================================================
  25.  
  26. SECTION [24]: Inheritance -- private and protected inheritance
  27.  
  28.  
  29. [24.1] How do you express "private inheritance"?
  30.  
  31. When you use : private instead of : public.  E.g.,
  32.  
  33.     class Foo : private Bar {
  34.     public:
  35.       // ...
  36.     };
  37.  
  38. ==============================================================================
  39.  
  40. [24.2] How are "private inheritance" and "composition" similar?
  41.  
  42. private inheritance is a syntactic variant of composition (has-a).
  43.  
  44. E.g., the "Car has-a Engine" relationship can be expressed using composition:
  45.  
  46.     class Engine {
  47.     public:
  48.       Engine(int numCylinders);
  49.       void start();                 // Starts this Engine
  50.     };
  51.  
  52.     class Car {
  53.     public:
  54.       Car() : e_(8) { }             // Initializes this Car with 8 cylinders
  55.       void start() { e_.start(); }  // Start this Car by starting its Engine
  56.     private:
  57.       Engine e_;                    // Car has-a Engine
  58.     };
  59.  
  60. The same "has-a" relationship can also be expressed using private inheritance:
  61.  
  62.     class Car : private Engine {    // Car has-a Engine
  63.     public:
  64.       Car() : Engine(8) { }         // Initializes this Car with 8 cylinders
  65.       Engine::start;                // Start this Car by starting its Engine
  66.     };
  67.  
  68. There are several similarities between these two forms of composition:
  69.  * In both cases there is exactly one Engine member object contained in a Car
  70.  * In neither case can users (outsiders) convert a Car* to an Engine*
  71.  
  72. There are also several distinctions:
  73.  * The first form is needed if you want to contain several Engines per Car
  74.  * The second form can introduce unnecessary multiple inheritance
  75.  * The second form allows members of Car to convert a Car* to an Engine*
  76.  * The second form allows access to the protected members of the base class
  77.  * The second form allows Car to override Engine's virtual[20] functions
  78.  
  79. Note that private inheritance is usually used to gain access into the
  80. protected: members of the base class, but this is usually a short-term solution
  81. (translation: a band-aid[24.3]).
  82.  
  83. ==============================================================================
  84.  
  85. [24.3] Which should I prefer: composition or private inheritance?
  86.  
  87. Use composition when you can, private inheritance when you have to.
  88.  
  89. Normally you don't want to have access to the internals of too many other
  90. classes, and private inheritance gives you some of this extra power (and
  91. responsibility).  But private inheritance isn't evil; it's just more expensive
  92. to maintain, since it increases the probability that someone will change
  93. something that will break your code.
  94.  
  95. A legitimate, long-term use for private inheritance is when you want to build a
  96. class Fred that uses code in a class Wilma, and the code from class Wilma needs
  97. to invoke member functions from your new class, Fred.  In this case, Fred calls
  98. non-virtuals in Wilma, and Wilma calls (usually pure virtuals[22.4]) in itself,
  99. which are overridden by Fred.  This would be much harder to do with
  100. composition.
  101.  
  102.     class Wilma {
  103.     protected:
  104.       void fredCallsWilma()
  105.         {
  106.           cout << "Wilma::fredCallsWilma()\n";
  107.           wilmaCallsFred();
  108.         }
  109.       virtual void wilmaCallsFred() = 0;   // A pure virtual function[22.4]
  110.     };
  111.  
  112.     class Fred : private Wilma {
  113.     public:
  114.       void barney()
  115.         {
  116.           cout << "Fred::barney()\n";
  117.           Wilma::fredCallsWilma();
  118.         }
  119.     protected:
  120.       virtual void wilmaCallsFred()
  121.         {
  122.           cout << "Fred::wilmaCallsFred()\n";
  123.         }
  124.     };
  125.  
  126. ==============================================================================
  127.  
  128. [24.4] Should I pointer-cast from a private derived class to its base class?
  129.  
  130. Generally, No.
  131.  
  132. From a member function or friend[14] of a privately derived class, the
  133. relationship to the base class is known, and the upward conversion from
  134. PrivatelyDer* to Base* (or PrivatelyDer& to Base&) is safe; no cast is needed
  135. or recommended.
  136.  
  137. However users of PrivateDer should avoid this unsafe conversion, since it is
  138. based on a private decision of PrivateDer, and is subject to change without
  139. notice.
  140.  
  141. ==============================================================================
  142.  
  143. [24.5] How is protected inheritance related to private inheritance?
  144.  
  145. Similarities: both allow overriding virtual[20] functions in the
  146. private/protected base class, neither claims the derived is a kind-of its base.
  147.  
  148. Dissimilarities: protected inheritance allows derived classes of derived
  149. classes to know about the inheritance relationship.  Thus your grand kids are
  150. effectively exposed to your implementation details.  This has both benefits (it
  151. allows subclasses of the protected derived class to exploit the relationship to
  152. the protected base class) and costs (the protected derived class can't change
  153. the relationship without potentially breaking further derived classes).
  154.  
  155. Protected inheritance uses the : protected syntax:
  156.  
  157.     class Car : protected Engine {
  158.     public:
  159.       // ...
  160.     };
  161.  
  162. ==============================================================================
  163.  
  164. [24.6] What are the access rules with private and protected inheritance?
  165.  
  166. Take these classes as examples:
  167.  
  168.     class B                    { /*...*/ };
  169.     class D_priv : private   B { /*...*/ };
  170.     class D_prot : protected B { /*...*/ };
  171.     class D_publ : public    B { /*...*/ };
  172.     class UserClass            { B b; /*...*/ };
  173.  
  174. None of the subclasses can access anything that is private in B.  In D_priv,
  175. the public and protected parts of B are private.  In D_prot, the public and
  176. protected parts of B are protected.  In D_publ, the public parts of B are
  177. public and the protected parts of B are protected (D_publ is-a-kind-of-a B).
  178. class UserClass can access only the public parts of B, which "seals off"
  179. UserClass from B.
  180.  
  181. To make a public member of B so it is public in D_priv or D_prot, state the
  182. name of the member with a B:: prefix.  E.g., to make member B::f(int,float)
  183. public in D_prot, you would say:
  184.  
  185.     class D_prot : protected B {
  186.     public:
  187.       B::f;    // Note: Not B::f(int,float)
  188.     };
  189.  
  190. ==============================================================================
  191.  
  192. SECTION [25]: Coding standards
  193.  
  194.  
  195. [25.1] What are some good C++ coding standards?
  196.  
  197. Thank you for reading this answer rather than just trying to set your own
  198. coding standards.
  199.  
  200. But beware that some people on comp.lang.c++ are very sensitive on this issue.
  201. Nearly every software engineer has, at some point, been exploited by someone
  202. who used coding standards as a "power play." Furthermore some attempts to set
  203. C++ coding standards have been made by those who didn't know what they were
  204. talking about, so the standards end up being based on what was the
  205. state-of-the-art when the standards setters where writing code.  Such
  206. impositions generate an attitude of mistrust for coding standards.
  207.  
  208. Obviously anyone who asks this question wants to be trained so they don't run
  209. off on their own ignorance, but nonetheless posting a question such as this one
  210. to comp.lang.c++ tends to generate more heat than light.
  211.  
  212. ==============================================================================
  213.  
  214. [25.2] Are coding standards necessary? Are they sufficient?
  215.  
  216. Coding standards do not make non-OO programmers into OO programmers; only
  217. training and experience do that.  If coding standards have merit, it is that
  218. they discourage the petty fragmentation that occurs when large organizations
  219. coordinate the activities of diverse groups of programmers.
  220.  
  221. But you really want more than a coding standard.  The structure provided by
  222. coding standards gives neophytes one less degree of freedom to worry about,
  223. which is good.  However pragmatic guidelines should go well beyond
  224. pretty-printing standards.  Organizations need a consistent philosophy of
  225. design and implementation.  E.g., strong or weak typing? references or pointers
  226. in interfaces? stream I/O or stdio? should C++ code call C code? vice versa?
  227. how should ABCs[22.3] be used? should inheritance be used as an implementation
  228. technique or as a specification technique? what testing strategy should be
  229. employed? inspection strategy? should interfaces uniformly have a get() and/or
  230. set() member function for each data member? should interfaces be designed from
  231. the outside-in or the inside-out? should errors be handled by try/catch/throw
  232. or by return codes? etc.
  233.  
  234. What is needed is a "pseudo standard" for detailed design. I recommend a
  235. three-pronged approach to achieving this standardization: training,
  236. mentoring[26.1], and libraries.  Training provides "intense instruction,"
  237. mentoring allows OO to be caught rather than just taught, and high quality C++
  238. class libraries provide "long term instruction." There is a thriving commercial
  239. market for all three kinds of "training." Advice by organizations who have been
  240. through the mill is consistent: Buy, Don't Build. Buy libraries, buy training,
  241. buy tools, buy consulting.  Companies who have attempted to become a
  242. self-taught tool-shop as well as an application/system shop have found success
  243. difficult.
  244.  
  245. Few argue that coding standards are "ideal," or even "good," however they are
  246. necessary in the kind of organizations/situations described above.
  247.  
  248. The following FAQs provide some basic guidance in conventions and styles.
  249.  
  250. ==============================================================================
  251.  
  252. [25.3] Should our organization determine coding standards from our C
  253.        experience?
  254.  
  255. No!
  256.  
  257. No matter how vast your C experience, no matter how advanced your C expertise,
  258. being a good C programmer does not make you a good C++ programmer.  Converting
  259. from C to C++ is more than just learning the syntax and semantics of the ++
  260. part of C++.  Organizations who want the promise of OO, but who fail to put the
  261. "OO" into "OO programming", are fooling themselves; the balance sheet will show
  262. their folly.
  263.  
  264. C++ coding standards should be tempered by C++ experts.  Asking comp.lang.c++
  265. is a start.  Seek out experts who can help guide you away from pitfalls.  Get
  266. training.  Buy libraries and see if "good" libraries pass your coding
  267. standards.  Do not set standards by yourself unless you have considerable
  268. experience in C++.  Having no standard is better than having a bad standard,
  269. since improper "official" positions "harden" bad brain traces.  There is a
  270. thriving market for both C++ training and libraries from which to pool
  271. expertise.
  272.  
  273. One more thing: whenever something is in demand, the potential for charlatans
  274. increases.  Look before you leap.  Also ask for student-reviews from past
  275. companies, since not even expertise makes someone a good communicator.
  276. Finally, select a practitioner who can teach, not a full time teacher who has a
  277. passing knowledge of the language/paradigm.
  278.  
  279. ==============================================================================
  280.  
  281. [25.4] Is the ?: operator evil since it can be used to create unreadable code?
  282.        [NEW!]
  283.  
  284. [Recently created (on 1/97).]
  285.  
  286. No, but as always, remember that readability is one of the most important
  287. things.
  288.  
  289. Some people feel the ?: ternary operator should be avoided because they find it
  290. confusing at times compared to the good old if statement.  In many cases ?:
  291. tends to make your code more difficult to read (and therefore you should
  292. replace those usages of ?: with if statements), but there are times when the ?:
  293. operator is clearer since it can emphasize what's really happening, rather than
  294. the fact that there's an if in there somewhere.
  295.  
  296. Let's start with a really simple case.  Suppose you need to print the result of
  297. a function call.  In that case you should put the real goal (printing) at the
  298. beginning of the line, and bury the function call within the line since it's
  299. relatively incidental (this left-right thing is based on the intuitive notion
  300. that most developers think the first thing on a line is the most important
  301. thing):
  302.  
  303.     // Preferred (emphasizes the major goal -- printing):
  304.     cout << funct();
  305.  
  306.     // Not as good (emphasizes the minor goal -- a function call):
  307.     functAndPrintOn(cout);
  308.  
  309. Now let's extend this idea to the ?: operator.  Suppose your real goal is to
  310. print something, but you need to do some incidental decision logic to figure
  311. out what should be printed.  Since the printing is the most important thing
  312. conceptually, we prefer to put it first on the line, and we prefer to bury the
  313. incidental decision logic.  In the example code below, variable n represents
  314. the number of senders of a message; the message itself is being printed to
  315. cout:
  316.  
  317.     int n = /*...*/;   // number of senders
  318.  
  319.     // Preferred (emphasizes the major goal -- printing):
  320.     cout << "Please get back to " << (n==1 ? "me" : "us") << " soon!\n";
  321.  
  322.     // Not as good (emphasizes the minor goal -- a decision):
  323.     cout << "Please get back to ";
  324.     if (n==1)
  325.       cout << "me";
  326.     else
  327.       cout << "us";
  328.     cout << " soon!\n";
  329.  
  330. All that being said, you can get pretty outrageous and unreadable code ("write
  331. only code") using various combinations of ?:, &&, ||, etc.  For example,
  332.  
  333.     // Preferred (obvious meaning):
  334.     if (f())
  335.       g();
  336.  
  337.     // Not as good (harder to understand):
  338.     f() && g();
  339.  
  340. Personally I think the explicit if example is clearer since it emphasizes the
  341. major thing that's going on (a decision based on the result of calling f())
  342. rather than the minor thing (calling f()).  In other words, the use of if here
  343. is good for precisely the same reason that it was bad above: we want to major
  344. on the majors and minor on the minors.
  345.  
  346. In any event, don't forget that readability is the goal (at least it's one of
  347. the goals).  Your goal should not be to avoid certain syntactic constructs such
  348. as ?: or && or || or if -- or even goto.  If you sink to the level of a
  349. "Standards Bigot," you'll ultimately embarass yourself since there are always
  350. counterexamples to any syntax-based rule.  If on the other hand you emphasize
  351. broad goals and guidelines (e.g., "major on the majors," or "put the most
  352. important thing first on the line," or even "make sure your code is obvious and
  353. readable"), you're usually much better off.
  354.  
  355. Code must be written to be read, not by the compiler, but by another human
  356. being.
  357.  
  358. ==============================================================================
  359.  
  360. [25.5] Should I declare locals in the middle of a function or at the top?
  361.  
  362. Declare near first use.
  363.  
  364. An object is initialized (constructed) the moment it is declared.  If you don't
  365. have enough information to initialize an object until half way down the
  366. function, you should create it half way down the function when it can be
  367. initialized correctly.  Don't initialize it to an "empty" value at the top then
  368. "assign" it later.  The reason for this is runtime performance.  Building an
  369. object correctly is faster than building it incorrectly and remodeling it
  370. later.  Simple examples show a factor of 350% speed hit for simple classes like
  371. String.  Your mileage may vary; surely the overall system degradation will be
  372. less that 350%, but there will be degradation.  Unnecessary degradation.
  373.  
  374. A common retort to the above is: "we'll provide set() member functions for
  375. every datum in our objects so the cost of construction will be spread out."
  376. This is worse than the performance overhead, since now you're introducing a
  377. maintenance nightmare.  Providing a set() member function for every datum is
  378. tantamount to public data: you've exposed your implementation technique to the
  379. world.  The only thing you've hidden is the physical names of your member
  380. objects, but the fact that you're using a List and a String and a float, for
  381. example, is open for all to see.
  382.  
  383. Bottom line: Locals should be declared near their first use.  Sorry that this
  384. isn't familiar to C experts, but new doesn't necessarily mean bad.
  385.  
  386. ==============================================================================
  387.  
  388. [25.6] What source-file-name convention is best? foo.cpp? foo.C? foo.cc?
  389.  
  390. If you already have a convention, use it.  If not, consult your compiler to see
  391. what the compiler expects.  Typical answers are: .C, .cc, .cpp, or .cxx
  392. (naturally the .C extension assumes a case-sensitive file system to distinguish
  393. .C from .c).
  394.  
  395. At Paradigm Shift, Inc., we have used both .cpp for our C++ source files, and
  396. we have also used .C.  In the latter case, we supply the compiler option forces
  397. .c files to be treated as C++ source files (-Tdp for IBM CSet++, -cpp for
  398. Zortech C++, -P for Borland C++, etc.) when porting to case-insensitive file
  399. systems.  None of these approaches have any striking technical superiority to
  400. the others; we generally use whichever technique is preferred by our customer
  401. (again, these issues are dominated by business considerations, not by technical
  402. considerations).
  403.  
  404. ==============================================================================
  405.  
  406. [25.7] What header-file-name convention is best? foo.H? foo.hh? foo.hpp?
  407.  
  408. If you already have a convention, use it.  If not, and if you don't need your
  409. editor to distinguish between C and C++ files, simply use .h.  Otherwise use
  410. whatever the editor wants, such as .H, .hh, or .hpp.
  411.  
  412. At Paradigm Shift, Inc., we tend to use either .hpp or .h for our C++ header
  413. files.
  414.  
  415. ==============================================================================
  416.  
  417. [25.8] Are there any lint-like guidelines for C++?
  418.  
  419. Yes, there are some practices which are generally considered dangerous.
  420. However none of these are universally "bad," since situations arise when even
  421. the worst of these is needed:
  422.  * A class Fred's assignment operator should return *this as a Fred& (allows
  423.    chaining of assignments)
  424.  * A class with any virtual[20] functions ought to have a virtual
  425.    destructor[20.4]
  426.  * A class with any of {destructor, assignment operator, copy constructor}
  427.    generally needs all 3
  428.  * A class Fred's copy constructor and assignment operator should have const in
  429.    the parameter: respectively Fred::Fred(const Fred&) and
  430.    Fred& Fred::operator= (const Fred&)
  431.  * When initializing an object's member objects in the constructor, always use
  432.    initialization lists rather than assignment.  The performance difference for
  433.    user-defined classes can be substantial (3x!)
  434.  * Assignment operators should make sure that self assignment[12.1] does
  435.    nothing, otherwise you may have a disaster[12.2].  In some cases, this may
  436.    require you to add an explicit test to your assignment operators[12.3].
  437.  * In classes that define both += and +, a += b and a = a + b should generally
  438.    do the same thing; ditto for the other identities of built-in types (e.g.,
  439.    a += 1 and ++a; p[i] and *(p+i); etc).  This can be enforced by writing the
  440.    binary operations using the op= forms.  E.g.,
  441.  
  442.        Fred operator+ (const Fred& a, const Fred& b)
  443.        {
  444.          Fred ans = a;
  445.          ans += b;
  446.          return ans;
  447.        }
  448.  
  449.    This way the "constructive" binary operators don't even need to be
  450. friends[14].  But it is sometimes possible to more efficiently implement common
  451. operations (e.g., if class Fred is actually String, and += has to
  452. reallocate/copy string memory, it may be better to know the eventual length
  453. from the beginning).
  454.  
  455. ==============================================================================
  456.  
  457. [25.9] Which is better: identifier names that_look_like_this or identifier
  458.        names thatLookLikeThis?
  459.  
  460. It's a precedent thing.  If you have a Pascal or Smalltalk background,
  461. youProbablySquashNamesTogether like this.  If you have an Ada background,
  462. You_Probably_Use_A_Large_Number_Of_Underscores like this.  If you have a
  463. Microsoft Windows background, you probably prefer the "Hungarian" style which
  464. means you jkuidsPrefix vndskaIdentifiers ncqWith ksldjfTheir nmdsadType.  And
  465. then there are the folks with a Unix C background, who abbr evthng n use vry
  466. srt idntfr nms.
  467.  
  468. So there is no universal standard.  If your organization has a particular
  469. coding standard for identifier names, use it.  But starting another Jihad over
  470. this will create a lot more heat than light.  From a business perspective,
  471. there are only two things that matter: The code should be generally readable,
  472. and everyone in the organization should use the same style.
  473.  
  474. Other than that, th difs r minr.
  475.  
  476. ==============================================================================
  477.  
  478. [25.10] Are there any other sources of coding standards? [UPDATED!]
  479.  
  480. [Recently rewrote and added more URLs (on 11/96).]
  481.  
  482. Yep, there are several.
  483.  
  484. Here are a few sources that you might be able to use as starting points for
  485. developing your organization's coding standards:
  486.  * A bunch of coding standards are provided at
  487.    http://fndaub.fnal.gov:8000/standards/standards.html
  488.  * The Ellemtel coding guidelines are available at
  489.    - http://web2.airmail.net/~rks/ellhome.htm
  490.    - http://www.rhi.hi.is/~harri/cpprules.html
  491.    - http://euagate.eua.ericsson.se/pub/eua/c++
  492.    - http://nestor.ceid.upatras.gr/programming/ellemtel/ellhome.htm
  493.    - http://www.doc.ic.ac.uk/lab/cplus/c++.rules/
  494.  * Todd Hoff's coding standard guidelines are available at
  495.    http://www.possibility.com/cpp.
  496.  
  497. Note: I do NOT warrant or endorse these URLs and/or their contents.  They are
  498. listed as a public service only.  I haven't checked their details, so I don't
  499. know if they'll help you or hurt you.  Caveat emptor.
  500.  
  501. ==============================================================================
  502.  
  503. SECTION [26]: Learning OO/C++
  504.  
  505.  
  506. [26.1] What is mentoring?
  507.  
  508. It's the most important tool in learning OO.
  509.  
  510. Object-oriented thinking is caught, not just taught.  Get cozy with someone who
  511. really knows what they're talking about, and try to get inside their head and
  512. watch them solve problems.  Listen.  Learn by emulating.
  513.  
  514. If you're working for a company, get them to bring someone in who can act as a
  515. mentor and guide.  We've seen gobs and gobs of money wasted by companies who
  516. "saved money" by simply buying their employees a book ("Here's a book; read it
  517. over the weekend; on Monday you'll be an OO developer").
  518.  
  519. ==============================================================================
  520.  
  521. [26.2] Should I learn C before I learn OO/C++?
  522.  
  523. Don't bother.
  524.  
  525. If your ultimate goal is to learn OO/C++ and you don't already know C, reading
  526. books or taking courses in C will not only waste your time, but it will teach
  527. you a bunch of things that you'll explicitly have to un-learn when you finally
  528. get back on track and learn OO/C++ (e.g., malloc()[16.3], printf()[15.1],
  529. unnecessary use of switch statements[20], error-code exception handling[17],
  530. unnecessary use of #define macros[9.3], etc.).
  531.  
  532. If you want to learn OO/C++, learn OO/C++.  Taking time out to learn C will
  533. waste your time and confuse you.
  534.  
  535. ==============================================================================
  536.  
  537. [26.3] Should I learn Smalltalk before I learn OO/C++?
  538.  
  539. Don't bother.
  540.  
  541. If your ultimate goal is to learn OO/C++ and you don't already know Smalltalk,
  542. reading books or taking courses in Smalltalk will not only waste your time, but
  543. it will teach you a bunch of things that you'll explicitly have to un-learn
  544. when you finally get back on track and learn OO/C++ (e.g., dynamic
  545. typing[27.3], non-subtyping inheritance[27.5], error-code exception
  546. handling[17], etc.).
  547.  
  548. Knowing a "pure" OO language doesn't make the transition to OO/C++ any easier.
  549. This is not a theory; I speak from experience (Paradigm Shift, Inc.,
  550. info@parashift.com, has trained and mentored literally thousands of software
  551. professionals in OO).  In fact, Smalltalk experience can make it harder for
  552. some people: they need to unlearn some rather deep notions about typing and
  553. inheritance in addition to needing to learn new syntax and idioms.  This
  554. unlearning process is especially painful and slow for those who cling to
  555. Smalltalk with religious zeal ("C++ is not like Smalltalk, therefore C++ is
  556. evil").
  557.  
  558. If you want to learn OO/C++, learn OO/C++.  Taking time out to learn Smalltalk
  559. will waste your time and confuse you.
  560.  
  561. Note: I sit on both the ANSI C++ (X3J16) and ANSI Smalltalk (X3J20)
  562. standardization committees[6.11].  I am not a language bigot[6.4].  I'm not
  563. saying C++ is better or worse than Smalltalk; I'm simply saying that they are
  564. different[27.1].
  565.  
  566. ==============================================================================
  567.  
  568. [26.4] Should I buy one book, or several?
  569.  
  570. At least two.
  571.  
  572. There are two categories of insight and knowledge in OO programming using C++.
  573. You're better off getting a "best of breed" book from each category rather than
  574. trying to find a single book that does an OK job at everything.  The two OO/C++
  575. programming categories are:
  576.  * C++ legality guides -- what you can and can't do in C++[26.6].
  577.  * C++ morality guides -- what you should and shouldn't do in C++[26.5].
  578.  
  579. Legality guides describe all language features with roughly the same level of
  580. emphasis; morality guides focus on those language features that you will use
  581. most often in typical programming tasks.  Legality guides tell you how to get a
  582. given feature past the compiler; morality guides tell you whether or not to use
  583. that feature in the first place.
  584.  
  585. Meta comments:
  586.  * Neither of these categories is optional.  You must have a good grasp of
  587.    both.
  588.  * These categories do not trade off against each other.  You shouldn't argue
  589.    in favor of one over the other.  They dove-tail.
  590.  
  591. ==============================================================================
  592.  
  593. [26.5] What are some best-of-breed C++ morality guides?
  594.  
  595. Here's my personal (subjective and selective) short-list of must-read C++
  596. morality guides, alphabetically by author:
  597.  * Cline and Lomow, C++ FAQs, 461 pgs, Addison-Wesley, 1995, ISBN
  598.    0-201-58958-3.  Covers 470 topics in a FAQ-like Q&A format.
  599.  * Meyers, Effective C++, 224 pgs, Addison-Wesley, 1992, ISBN 0-201-56364-9.
  600.    Covers 50 topics in a short essay format.
  601.  * Meyers, More Effective C++, 336 pgs, Addison-Wesley, 1996, ISBN
  602.    0-201-63371-X.  Covers 35 topics in a short essay format.
  603.  
  604. Similarities: All three books are extensively illustrated with code examples.
  605. All three are excellent, insightful, useful, gold plated books.  All three have
  606. excellent sales records.
  607.  
  608. Differences: Cline and Lomow's examples are complete, working programs rather
  609. than code fragments or standalone classes.  Meyers contains numerous
  610. line-drawings that illustrate the points.
  611.  
  612. ==============================================================================
  613.  
  614. [26.6] What are some best-of-breed C++ legality guides?
  615.  
  616. Here's my personal (subjective and selective) short-list of must-read C++
  617. legality guides, alphabetically by author:
  618.  * Lippman, C++ Primer, Second Edition, 614 pgs, Addison-Wesley, 1991, ISBN
  619.    0-201-54848-8.  Very readable/approachable.
  620.  * Stroustrup, The C++ Programming Language, Second Edition, 646 pgs,
  621.    Addison-Wesley, 1991, ISBN 0-201-53992-6.  Covers a lot of ground.
  622.  
  623. Similarities: Both books are excellent overviews of almost every language
  624. feature.  I reviewed them for back-to-back issues of C++ Report, and I said
  625. that they are both top notch, gold plated, excellent books.  Both have
  626. excellent sales records.
  627.  
  628. Differences: If you don't know C, Lippman's book is better for you.  If you
  629. know C and you want to cover a lot of ground quickly, Stroustrup's book is
  630. better for you.
  631.  
  632. ==============================================================================
  633.  
  634. [26.7] Are there other OO books that are relevant to OO/C++?
  635.  
  636. Yes! Tons!
  637.  
  638. The morality[26.5] and legality[26.6] categories listed above were for OO
  639. programming.  The areas of OO analysis and OO design are also relevant, and
  640. have their own best-of-breed books.
  641.  
  642. There are tons and tons of good books in these other areas.  I'll only mention
  643. the book that's closest to the code on the grand spectrum from specification
  644. down to code (this is, after all, the FAQ on C++, not the FAQ on OO analysis or
  645. OO design).  Here's my personal (subjective and selective) short-list of
  646. must-read books on OO design patterns:
  647.  * Gamma et al., Design Patterns, 395 pgs, Addison-Wesley, 1995, ISBN
  648.    0-201-63361-2.  Describes "patterns" that commonly show up in good OO
  649.    designs.  You must read this book if you intend to do OO design work.
  650.  
  651. ==============================================================================
  652.  
  653. SECTION [27]: Learning C++ if you already know Smalltalk
  654.  
  655.  
  656. [27.1] What's the difference between C++ and Smalltalk?
  657.  
  658. Both fully support the OO paradigm.  Neither is categorically and universally
  659. "better" than the other[6.4].  But there are differences.  The most important
  660. differences are:
  661.  * Static typing vs. dynamic typing[27.2]
  662.  * Whether inheritance must be used only for subtyping[27.5]
  663.  * Value vs. reference semantics[28]
  664.  
  665. Note: Many new C++ programmers come from a Smalltalk background.  If that's
  666. you, this section will tell you the most important things you need know to make
  667. your transition.  Please don't get the notion that either language is somehow
  668. "inferior" or "bad"[6.4], or that this section is promoting one language over
  669. the other (I am not a language bigot; I serve on both the ANSI C++ and ANSI
  670. Smalltalk standardization committees[6.11]).  Instead, this section is designed
  671. to help you understand (and embrace!) the differences.
  672.  
  673. ==============================================================================
  674.  
  675. [27.2] What is "static typing," and how is it similar/dissimilar to Smalltalk?
  676.  
  677. Static typing says the compiler checks the type safety of every operation
  678. statically (at compile-time), rather than to generate code which will check
  679. things at run-time.  For example, with static typing, the signature matching
  680. for function arguments is checked at compile time, not at run-time.  An
  681. improper match is flagged as an error by the compiler, not by the run-time
  682. system.
  683.  
  684. In OO code, the most common "typing mismatch" is invoking a member function
  685. against an object which isn't prepared to handle the operation.  E.g., if class
  686. Fred has member function f() but not g(), and fred is an instance of class
  687. Fred, then fred.f() is legal and fred.g() is illegal.  C++ (statically typed)
  688. catches the error at compile time, and Smalltalk (dynamically typed) catches
  689. the error at run-time.  (Technically speaking, C++ is like Pascal --pseudo
  690. statically typed-- since pointer casts and unions can be used to violate the
  691. typing system; which reminds me: only use pointer casts and unions as often as
  692. you use gotos).
  693.  
  694. ==============================================================================
  695.  
  696. [27.3] Which is a better fit for C++: "static typing" or "dynamic typing"?
  697.  
  698. [For context, please read the previous FAQ[27.2]].
  699.  
  700. If you want to use C++ most effectively, use it as a statically typed language.
  701.  
  702. C++ is flexible enough that you can (via pointer casts, unions, and #define
  703. macros) make it "look" like Smalltalk.  But don't.  Which reminds me: try to
  704. avoid #define[9.3].
  705.  
  706. There are places where pointer casts and unions are necessary and even
  707. wholesome, but they should be used carefully and sparingly.  A pointer cast
  708. tells the compiler to believe you.  An incorrect pointer cast might corrupt
  709. your heap, scribble into memory owned by other objects, call nonexistent member
  710. functions, and cause general failures.  It's not a pretty sight.  If you avoid
  711. these and related constructs, you can make your C++ code both safer and faster,
  712. since anything that can be checked at compile time is something that doesn't
  713. have to be done at run-time.
  714.  
  715. If you're interested in using a pointer cast, use the new style pointer casts.
  716. The most common example of these is to change old-style pointer casts such as
  717. (X*)p into new-style dynamic casts such as dynamic_cast<X*>(p), where p is a
  718. pointer and X is a type.  In addition to dynamic_cast, there is static_cast and
  719. const_cast, but dynamic_cast is the one that simulates most of the advantages
  720. of dynamic typing (the other is the typeid() construct; for example,
  721. typeid(*p).name() will return the name of the type of *p).
  722.  
  723. ==============================================================================
  724.  
  725. [27.4] How do you use inheritance in C++, and is that different from Smalltalk?
  726.  
  727. Some people believe that the purpose of inheritance is code reuse.  In C++,
  728. this is wrong.  Stated plainly, "inheritance is not for code reuse."
  729.  
  730. The purpose of inheritance in C++ is to express interface compliance
  731. (subtyping), not to get code reuse.  In C++, code reuse usually comes via
  732. composition rather than via inheritance.  In other words, inheritance is mainly
  733. a specification technique rather than an implementation technique.
  734.  
  735. This is a major difference with Smalltalk, where there is only one form of
  736. inheritance (C++ provides private inheritance to mean "share the code but don't
  737. conform to the interface", and public inheritance to mean "kind-of").  The
  738. Smalltalk language proper (as opposed to coding practice) allows you to have
  739. the effect of "hiding" an inherited method by providing an override that calls
  740. the "does not understand" method.  Furthermore Smalltalk allows a conceptual
  741. "is-a" relationship to exist apart from the subclassing hierarchy (subtypes
  742. don't have to be subclasses; e.g., you can make something that is-a Stack yet
  743. doesn't inherit from class Stack).
  744.  
  745. In contrast, C++ is more restrictive about inheritance: there's no way to make
  746. a "conceptual is-a" relationship without using inheritance (the C++ work-around
  747. is to separate interface from implementation via ABCs[22.3]).  The C++ compiler
  748. exploits the added semantic information associated with public inheritance to
  749. provide static typing.
  750.  
  751. ==============================================================================
  752.  
  753. [27.5] What are the practical consequences of differences in Smalltalk/C++
  754.        inheritance?
  755.  
  756. [For context, please read the previous FAQ[27.4]].
  757.  
  758. Smalltalk lets you make a subtype that isn't a subclass, and allows you to make
  759. a subclass that isn't a subtype.  This allows Smalltalk programmers to be very
  760. carefree in putting data (bits, representation, data structure) into a class
  761. (e.g., you might put a linked list into class Stack).  After all, if someone
  762. wants an array-based-Stack, they don't have to inherit from Stack; they could
  763. inherit such a class from Array if desired, even though an ArrayBasedStack is
  764. not a kind-of Array!
  765.  
  766. In C++, you can't be nearly as carefree.  Only mechanism (member function
  767. code), but not representation (data bits) can be overridden in subclasses.
  768. Therefore you're usually better off not putting the data structure in a class.
  769. This leads to a stronger reliance on abstract base classes[22.3].
  770.  
  771. I like to think of the difference between an ATV and a Maseratti.  An ATV (all
  772. terrain vehicle) is more fun, since you can "play around" by driving through
  773. fields, streams, sidewalks, and the like.  A Maseratti, on the other hand, gets
  774. you there faster, but it forces you to stay on the road.  My advice to C++
  775. programmers is simple: stay on the road.  Even if you're one of those people
  776. who like the "expressive freedom" to drive through the bushes, don't do it in
  777. C++; it's not a good fit.
  778.  
  779. ==============================================================================
  780.  
  781. SECTION [28]: Reference and value semantics
  782.  
  783.  
  784. [28.1] What is value and/or reference semantics, and which is best in C++?
  785.  
  786. With reference semantics, assignment is a pointer-copy (i.e., a reference).
  787. Value (or "copy") semantics mean assignment copies the value, not just the
  788. pointer.  C++ gives you the choice: use the assignment operator to copy the
  789. value (copy/value semantics), or use a pointer-copy to copy a pointer
  790. (reference semantics).  C++ allows you to override the assignment operator to
  791. do anything your heart desires, however the default (and most common) choice is
  792. to copy the value.
  793.  
  794. Pros of reference semantics: flexibility and dynamic binding (you get dynamic
  795. binding in C++ only when you pass by pointer or pass by reference, not when you
  796. pass by value).
  797.  
  798. Pros of value semantics: speed.  "Speed" seems like an odd benefit to for a
  799. feature that requires an object (vs. a pointer) to be copied, but the fact of
  800. the matter is that one usually accesses an object more than one copies the
  801. object, so the cost of the occasional copies is (usually) more than offset by
  802. the benefit of having an actual object rather than a pointer to an object.
  803.  
  804. There are three cases when you have an actual object as opposed to a pointer to
  805. an object: local objects, global/static objects, and fully contained member
  806. objects in a class.  The most important of these is the last ("composition").
  807.  
  808. More info about copy-vs-reference semantics is given in the next FAQs.  Please
  809. read them all to get a balanced perspective.  The first few have intentionally
  810. been slanted toward value semantics, so if you only read the first few of the
  811. following FAQs, you'll get a warped perspective.
  812.  
  813. Assignment has other issues (e.g., shallow vs. deep copy) which are not covered
  814. here.
  815.  
  816. ==============================================================================
  817.  
  818. [28.2] What is "virtual data," and how-can / why-would I use it in C++?
  819.  
  820. virtual data allows a derived class to change the exact class of a base class's
  821. member object.  virtual data isn't strictly "supported" by C++, however it can
  822. be simulated in C++.  It ain't pretty, but it works.
  823.  
  824. To simulate virtual data in C++, the base class must have a pointer to the
  825. member object, and the derived class must provide a new object to be pointed to
  826. by the base class's pointer.  The base class would also have one or more normal
  827. constructors that provide their own referent (again via new), and the base
  828. class's destructor would delete the referent.
  829.  
  830. For example, class Stack might have an Array member object (using a pointer),
  831. and derived class StretchableStack might override the base class member data
  832. from Array to StretchableArray.  For this to work, StretchableArray would have
  833. to inherit from Array, so Stack would have an Array*.  Stack's normal
  834. constructors would initialize this Array* with a new Array, but Stack would
  835. also have a (possibly protected:) constructor that would accept an Array* from
  836. a derived class.  StretchableArray's constructor would provide a
  837. new StretchableArray to this special constructor.
  838.  
  839. Pros:
  840.  * Easier implementation of StretchableStack (most of the code is inherited)
  841.  * Users can pass a StretchableStack as a kind-of Stack
  842.  
  843. Cons:
  844.  * Adds an extra layer of indirection to access the Array
  845.  * Adds some extra freestore allocation overhead (both new and delete)
  846.  * Adds some extra dynamic binding overhead (reason given in next FAQ)
  847.  
  848. In other words, we succeeded at making our job easier as the implementer of
  849. StretchableStack, but all our users pay for it[28.5].  Unfortunately the extra
  850. overhead was imposed on both users of StretchableStack and on users of Stack.
  851.  
  852. Please read the rest of this section.  (You will not get a balanced perspective
  853. without the others.)
  854.  
  855. ==============================================================================
  856.  
  857. [28.3] What's the difference between virtual data and dynamic data?
  858.  
  859. The easiest way to see the distinction is by an analogy with virtual
  860. functions[20]: A virtual member function means the declaration (signature) must
  861. stay the same in subclasses, but the definition (body) can be overridden.  The
  862. overriddenness of an inherited member function is a static property of the
  863. subclass; it doesn't change dynamically throughout the life of any particular
  864. object, nor is it possible for distinct objects of the subclass to have
  865. distinct definitions of the member function.
  866.  
  867. Now go back and re-read the previous paragraph, but make these substitutions:
  868.  * "member function" --> "member object"
  869.  * "signature" --> "type"
  870.  * "body" --> "exact class"
  871.  
  872. After this, you'll have a working definition of virtual data.
  873.  
  874. Another way to look at this is to distinguish "per-object" member functions
  875. from "dynamic" member functions.  A "per-object" member function is a member
  876. function that is potentially different in any given instance of an object, and
  877. could be implemented by burying a function pointer in the object; this pointer
  878. could be const, since the pointer will never be changed throughout the object's
  879. life.  A "dynamic" member function is a member function that will change
  880. dynamically over time; this could also be implemented by a function pointer,
  881. but the function pointer would not be const.
  882.  
  883. Extending the analogy, this gives us three distinct concepts for data members:
  884.  * virtual data: the definition (class) of the member object is overridable in
  885.    subclasses provided its declaration ("type") remains the same, and this
  886.    overriddenness is a static property of the subclass
  887.  * per-object-data: any given object of a class can instantiate a different
  888.    conformal (same type) member object upon initialization (usually a "wrapper"
  889.    object), and the exact class of the member object is a static property of
  890.    the object that wraps it
  891.  * dynamic-data: the member object's exact class can change dynamically over
  892.    time
  893.  
  894. The reason they all look so much the same is that none of this is "supported"
  895. in C++.  It's all merely "allowed," and in this case, the mechanism for faking
  896. each of these is the same: a pointer to a (probably abstract) base class.  In a
  897. language that made these "first class" abstraction mechanisms, the difference
  898. would be more striking, since they'd each have a different syntactic variant.
  899.  
  900. ==============================================================================
  901.  
  902. [28.4] Should I normally use pointers to freestore allocated objects for my
  903.        data members, or should I use "composition"?
  904.  
  905. Composition.
  906.  
  907. Your member objects should normally be "contained" in the composite object (but
  908. not always; "wrapper" objects are a good example of where you want a
  909. pointer/reference; also the N-to-1-uses-a relationship needs something like a
  910. pointer/reference).
  911.  
  912. There are three reasons why fully contained member objects ("composition") has
  913. better performance than pointers to freestore-allocated member objects:
  914.  * Extra layer of indirection every time you need to access the member object
  915.  * Extra freestore allocations (new in constructor, delete in destructor)
  916.  * Extra dynamic binding (reason given below)
  917.  
  918. ==============================================================================
  919.  
  920. [28.5] What are relative costs of the 3 performance hits associated with
  921.        allocating member objects from the freestore?
  922.  
  923. The three performance hits are enumerated in the previous FAQ:
  924.  * By itself, an extra layer of indirection is small potatoes
  925.  * Freestore allocations can be a performance issue (the performance of the
  926.    typical implementation of malloc() degrades when there are many allocations;
  927.    OO software can easily become "freestore bound" unless you're careful)
  928.  * The extra dynamic binding comes from having a pointer rather than an object.
  929.    Whenever the C++ compiler can know an object's exact class, virtual[20]
  930.    function calls can be statically bound, which allows inlining.  Inlining
  931.    allows zillions (would you believe half a dozen :-) optimization
  932.    opportunities such as procedural integration, register lifetime issues, etc.
  933.    The C++ compiler can know an object's exact class in three circumstances:
  934.    local variables, global/static variables, and fully-contained member objects
  935.  
  936. Thus fully-contained member objects allow significant optimizations that
  937. wouldn't be possible under the "member objects-by-pointer" approach.  This is
  938. the main reason that languages which enforce reference-semantics have
  939. "inherent" performance challenges.
  940.  
  941. Note: Please read the next three FAQs to get a balanced perspective!
  942.  
  943. ==============================================================================
  944.  
  945. [28.6] Are "inline virtual" member functions ever actually "inlined"?
  946.  
  947. Occasionally...
  948.  
  949. When the object is referenced via a pointer or a reference, a call to a
  950. virtual[20] function cannot be inlined, since the call must be resolved
  951. dynamically.  Reason: the compiler can't know which actual code to call until
  952. run-time (i.e., dynamically), since the code may be from a derived class that
  953. was created after the caller was compiled.
  954.  
  955. Therefore the only time an inline virtual call can be inlined is when the
  956. compiler knows the "exact class" of the object which is the target of the
  957. virtual function call.  This can happen only when the compiler has an actual
  958. object rather than a pointer or reference to an object.  I.e., either with a
  959. local object, a global/static object, or a fully contained object inside a
  960. composite.
  961.  
  962. Note that the difference between inlining and non-inlining is normally much
  963. more significant than the difference between a regular function call and a
  964. virtual function call.  For example, the difference between a regular function
  965. call and a virtual function call is often just two extra memory references, but
  966. the difference between an inline function and a non-inline function can be as
  967. much as an order of magnitude (for zillions of calls to insignificant member
  968. functions, loss of inlining virtual functions can result in 25X speed
  969. degradation! [Doug Lea, "Customization in C++," proc Usenix C++ 1990]).
  970.  
  971. A practical consequence of this insight: don't get bogged down in the endless
  972. debates (or sales tactics!) of compiler/language vendors who compare the cost
  973. of a virtual function call on their language/compiler with the same on another
  974. language/compiler.  Such comparisons are largely meaningless when compared with
  975. the ability of the language/compiler to "inline expand" member function calls.
  976. I.e., many language implementation vendors make a big stink about how good
  977. their dispatch strategy is, but if these implementations don't inline member
  978. function calls, the overall system performance would be poor, since it is
  979. inlining --not dispatching-- that has the greatest performance impact.
  980.  
  981. Note: Please read the next two FAQs to see the other side of this coin!
  982.  
  983. ==============================================================================
  984.  
  985. [28.7] Sounds like I should never use reference semantics, right?
  986.  
  987. Wrong.
  988.  
  989. Reference semantics are A Good Thing.  We can't live without pointers.  We just
  990. don't want our s/w to be One Gigantic Rats Nest Of Pointers.  In C++, you can
  991. pick and choose where you want reference semantics (pointers/references) and
  992. where you'd like value semantics (where objects physically contain other
  993. objects etc).  In a large system, there should be a balance.  However if you
  994. implement absolutely everything as a pointer, you'll get enormous speed hits.
  995.  
  996. Objects near the problem skin are larger than higher level objects.  The
  997. identity of these "problem space" abstractions is usually more important than
  998. their "value." Thus reference semantics should be used for problem-space
  999. objects.
  1000.  
  1001. Note that these problem space objects are normally at a higher level of
  1002. abstraction than the solution space objects, so the problem space objects
  1003. normally have a relatively lower frequency of interaction.  Therefore C++ gives
  1004. us an ideal situation: we choose reference semantics for objects that need
  1005. unique identity or that are too large to copy, and we can choose value
  1006. semantics for the others.  Thus the highest frequency objects will end up with
  1007. value semantics, since we install flexibility where it doesn't hurt us (only),
  1008. and we install performance where we need it most!
  1009.  
  1010. These are some of the many issues the come into play with real OO design.
  1011. OO/C++ mastery takes time and high quality training.  If you want a powerful
  1012. tool, you've got to invest.
  1013.  
  1014. Don't stop now! Read the next FAQ too!!
  1015.  
  1016. ==============================================================================
  1017.  
  1018. [28.8] Does the poor performance of reference semantics mean I should
  1019.        pass-by-value?
  1020.  
  1021. Nope.
  1022.  
  1023. The previous FAQ were talking about member objects, not parameters.  Generally,
  1024. objects that are part of an inheritance hierarchy should be passed by reference
  1025. or by pointer, not by value, since only then do you get the (desired) dynamic
  1026. binding (pass-by-value doesn't mix with inheritance, since larger subclass
  1027. objects get "sliced" when passed by value as a base class object).
  1028.  
  1029. Unless compelling reasons are given to the contrary, member objects should be
  1030. by value and parameters should be by reference.  The discussion in the previous
  1031. few FAQs indicates some of the "compelling reasons" for when member objects
  1032. should be by reference.
  1033.  
  1034. ==============================================================================
  1035.  
  1036.